package com.blockchain.securewallet.model;

import android.util.Log;

import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.crypto.HDUtils;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.bitcoinj.wallet.Wallet;
import org.spongycastle.util.encoders.Hex;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;


public class BitCoinHDWallet {

    private static final String TAG = "Wallet.BitCoin";

    public static final String PATH_BITCOIN = "M/44H/0H/0H/0/0";
    private static NetworkParameters params = MainNetParams.get();
    //private static NetworkParameters params = TestNet3Params.get();

    private String priKey;
    private String pubKey;
    public String address;
    private String words;
    private String password;

    public BitCoinHDWallet(Wallet wallet) {

    }
    public BitCoinHDWallet(String address,String publicKey,String privateKey,String words,String password){
        this.address = address;
        this.password = password;
        this.priKey = privateKey;
        this.pubKey = publicKey;
        this.words = words;
    }

    public static BitCoinHDWallet createWallet(String data, String passphrase) throws UnreadableWalletException {
        //data = "sword acquire little despair wave swear during expect target science banana eyebrow";
        long creationTimeSeconds = System.currentTimeMillis() / 1000;
        List<String> listWords = Arrays.asList(data.split("\\s+"));
        DeterministicSeed seed = new DeterministicSeed(listWords, null, passphrase, creationTimeSeconds);
        DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
        keyChain.getKeyByPath(HDUtils.parsePath(PATH_BITCOIN),true);

        DeterministicSeed ds = new DeterministicSeed(listWords, null, "", creationTimeSeconds);
        Log.i(TAG, Hex.toHexString(ds.getSeedBytes()));
        DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(ds).build();
        byte[] privateKeyBtc = deterministicKeyChain.getKeyByPath(HDUtils.parsePath("M/44H/0H/0H/0/0"), true).getPrivKeyBytes();
        ECKey ecKey = ECKey.fromPrivate(privateKeyBtc);
        ecKey = ECKey.fromPrivate(ecKey.getPrivKeyBytes());
        String publicKey = Numeric.toHexStringNoPrefixZeroPadded(new BigInteger(ecKey.getPubKey()),66);
        String privateKey = ecKey.getPrivateKeyEncoded(params).toString();
        String address = ecKey.toAddress(params).toString();
        Log.i(TAG,"pub:"+publicKey+"\npriv:"+privateKey+" \naddress:"+address);
        return new BitCoinHDWallet(address,publicKey,privateKey,data,passphrase);
    }

//    public String signedTransactionData(List<UnSpent> items,
//                                        long value,
//                                        long fee,
//                                        String to,
//                                        String password) {
//        Transaction transaction = new Transaction(params);
//        DumpedPrivateKey privateKey = DumpedPrivateKey.fromBase58(params,priKey);
//        ECKey ecKey = privateKey.getKey();
//        long total = 0L;
//        List<UTXO> utxos = new ArrayList<>();
//        for (UnSpent item:items) {
//            if(total>value+fee) {
//                break;
//            }
//
//            UTXO utxo = new UTXO(Sha256Hash.wrap(item.getTxid()),
//                    item.getOutputNo(),
//                    Coin.valueOf(item.getValue()),
//                    item.getConfirmations(),
//                    true,
//                    new Script(HEX.decode(item.getScript())));
//            utxos.add(utxo);
//            total += item.getValue();
//        }
//        transaction.addOutput(Coin.valueOf(value), Address.fromBase58(params,to));
//        long leave = total - value - fee;
//        if(leave>0) {
//            transaction.addOutput(Coin.valueOf(leave),Address.fromBase58(params,address));
//        }
//
//        for (UTXO u:utxos) {
//            TransactionOutPoint outPoint = new TransactionOutPoint(params,u.getIndex(),u.getHash());
//            transaction.addSignedInput(outPoint, u.getScript(), ecKey, Transaction.SigHash.ALL, true);
//        }
//        return HEX.encode(transaction.bitcoinSerialize());
//    }
}
